package com.nh.glory.admin.modular.system.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.nh.glory.core.R;
import com.nh.glory.core.node.INode;
import com.nh.glory.core.util.Func;
import com.nh.glory.data.model.Role;
import com.nh.glory.data.vo.RoleVO;
import com.nh.glory.ware.service.system.RoleService;
import com.nh.glory.ware.support.Condition;
import com.nh.glory.ware.wrapper.RoleWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;
import java.util.Map;

@RestController
@Slf4j
@RequestMapping("/roles")
public class RoleController {
    @Autowired
    private RoleService roleService;

    @GetMapping
    public R<List<INode>> list(@RequestParam Map<String, Object> role) {
        QueryWrapper<Role> queryWrapper = Condition.getQueryWrapper(role, Role.class);
        List<Role> list = roleService.list(queryWrapper);
        RoleWrapper roleWrapper = new RoleWrapper(roleService);
        return R.ok(roleWrapper.listNodeVO(list));
    }

    @GetMapping("{id}")
    public R<RoleVO> detail(@PathVariable Long id) {
        Role role = roleService.getById(id);
        RoleWrapper roleWrapper = new RoleWrapper(roleService);
        return R.ok(roleWrapper.entityVO(role));
    }

    /**
     * 获取角色树形结构
     */
    @GetMapping("/tree")
    public R<List<RoleVO>> tree() {
        List<RoleVO> tree = roleService.tree();
        return R.ok(tree);
    }

    /**
     * 新增或修改
     */
    @PostMapping()
    public R submit(@Valid @RequestBody Role role) {
        if (role.getId() == null) {
            if (role.getParentId() == null) role.setParentId(0L);
            if (role.getDeleted() == null) role.setDeleted(0);
        }
        return R.status(roleService.saveOrUpdate(role));
    }

    /**
     * 删除
     */
    @DeleteMapping()
    public R remove(@RequestParam String ids) {
        List<Long> list = Func.toLongList(ids);
        if (list.contains(1L)) {
            return R.fail(400, "不能删除管理员组");
        }
        return R.status(roleService.removeByIds(list));
    }

    @PostMapping("/grant")
    public R grant(@RequestParam String roleIds, @RequestParam String menuIds) {
        boolean temp = roleService.grant(Func.toLongList(roleIds), Func.toLongList(menuIds));
        return R.status(temp);
    }


}
